<?php
/**
 * gird tool form that if table where has status column
 * User：liujun
 * Date：2022/3/6
 * Time：7:22 AM
 */

namespace Encore\Admin\Grid\Tools;

use Encore\Admin\Admin;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Str;

class StatusFilterTab extends AbstractTool
{
    protected $model;

    protected $view = 'admin::grid.actions.statusfiltertab';
    protected $statusField;

    /**
     * the model of table
     * @param Model $model
     * @param string|null $statusField
     */
    public function __construct(?Model $model = null, ?string $statusField = 'status')
    {
        $this->model = $model;
        $this->statusField = $statusField;
    }

    protected function script(): string
    {
        $url = Request::fullUrlWithQuery([$this->statusField => '_status_']);
        return <<<EOT
$('input:radio.sFilter').change(function () {
    var url = "$url".replace('_status_', $(this).val());
    $.pjax({container:'#pjax-container', url: url });
});
$(document).on('change','.statusFilter',function () {
    var url = "$url".replace('_status_', $(this).val());
    $.pjax({container:'#pjax-container', url: url });
});
EOT;
    }

    public function render(): string
    {
        Admin::script($this->script());
        $statusCount = $this->model::groupBy($this->statusField)
            ->get([\DB::raw("count($this->statusField) as count,$this->statusField")])->pluck('count', $this->statusField)->toArray();
        $options[''] = '全部 (' . array_sum(array_values($statusCount)) . ')';

        $statuses = Str::of($this->statusField)->camel()->plural();
        foreach ($this->model::$$statuses as $key => $status) {
            $count = $statusCount[$key] ?? null;
            $options[$key] = $status . " {$count}";
        }
        $statusField = $this->statusField;
        return view($this->view, compact('options', 'statusField'))->render();
    }
}